﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Moonwish.Core;
using Moonwish.Core.EntityCore;
using Moonwish.Foundation.DataEntity;

namespace Moonwish.Foundation.ValueObjects
{
    /// <summary>
    /// 值对象分类集合，by zhlin 2011-08-12
    /// </summary>
    public class ValueObjectClassCollection : NotificationObjectCollection<ValueObjectClass>
    {
        private readonly ValueObjectModel _model;

        public ValueObjectClassCollection(){}

        internal ValueObjectClassCollection(ValueObjectModel model)
        {
            _model = model;
        }

        public override void Add(ValueObjectClass item)
        {
            if (item.DataStatus != DataStatus.New || item.Entity.ChangeTracker.State != ObjectState.Added)
            {
                throw new InvalidOperationException(string.Format("值对象分类“{0}”不是新增状态，无法添加。", item.Name));
            }
            _model.ValueObjectProxy.AddValueObjectClassCompleted += AddValueObjectClassCompleted;
            _model.ValueObjectProxy.AddValueObjectClassAsync(new ObservableCollection<V_FDT_ValueObjectClass> { item.Entity }, "Default", item);
        }

        void AddValueObjectClassCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null) return;

                var item = (ValueObjectClass)e.UserState;

                item.Model = _model;

                // 加入到业务数据集合。
                base.BaseAdd(item);

                var data = _model.CacheVoClass[_model.CacheVoClass.CurrentKey];

                // 加入到实体集合
                data.Add(item.Entity);

                item.AcceptChanges();

                
            }
            finally
            {
                _model.ValueObjectProxy.AddValueObjectClassCompleted -= AddValueObjectClassCompleted;
                
                InvokeAddCompleted(this, e);
            }
        }

        /// <summary>
        /// 用于Model查询时使用，不通知(NotifyChanged)。
        /// </summary>
        /// <param name="item"></param>
        internal new void BaseAdd(ValueObjectClass item)
        {
            BaseAdd(item, false);
        }

        public override void Remove(ValueObjectClass item)
        {
            if (item.DataStatus != DataStatus.New )
            {
                throw new InvalidOperationException(string.Format("值对象分类“{0}”不是新增状态，无法删除。", item.Name));
            }
            _model.ValueObjectProxy.DeleteValueObjectClassCompleted += DeleteValueObjectClassCompleted;
            _model.ValueObjectProxy.DeleteValueObjectClassAsync(new ObservableCollection<string> { item.Id }, "Default", item);
        }

        void DeleteValueObjectClassCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null) return;

                if (e.UserState is ValueObjectClass)
                {
                    var item = (ValueObjectClass)e.UserState;

                    BaseRemove(item);

                    var data = _model.CacheVoClass[_model.CacheVoClass.CurrentKey];

                    if (data.Contains(item.Entity))
                    {
                        data.Remove(item.Entity);
                    }
                }
                else if (e.UserState is IEnumerable<ValueObjectClass>)
                {
                    var items = (IEnumerable<ValueObjectClass>)e.UserState;

                    var data = _model.CacheVoClass[_model.CacheVoClass.CurrentKey];

                    foreach (var item in items)
                    {
                        BaseRemove(item);

                        if (data.Contains(item.Entity))
                        {
                            data.Remove(item.Entity);
                        }
                    }
                }

                AcceptChanges();
            }
            finally
            {
                _model.ValueObjectProxy.DeleteValueObjectClassCompleted -= DeleteValueObjectClassCompleted;

                InvokeRemoveCompleted(this, e);
            }
        }

        public override void Remove(IEnumerable<ValueObjectClass> items)
        {
            var ids = new ObservableCollection<string>();
            foreach (var item in items)
            {
                if (item.DataStatus != DataStatus.New)
                {
                    throw new InvalidOperationException(string.Format("值对象“{0}”不是新增状态，无法删除。", item.Name));
                }
                ids.Add(item.Id);
            }
            if (ids.Count > 0)
            {
                _model.ValueObjectProxy.DeleteValueObjectClassCompleted += DeleteValueObjectClassCompleted;
                _model.ValueObjectProxy.DeleteValueObjectClassAsync(ids, "Default", items);
            }
        }

        public override void Remove(string key)
        {
            Remove(this[key]);
        }

        public override void AcceptChanges()
        {
            foreach (var item in this)
            {
                item.AcceptChanges();
            }
        }

        protected override string GetKeyForItem(ValueObjectClass item)
        {
            return item.Id;
        }
    }
}
